import json
import re
import execjs
import os

from loguru import logger

from com.arcfox.school.processor.base_processor import BaseProcessor
from com.arcfox.middleware import async_mysql_middleware as db


class RuanKeSchoolProcessor(BaseProcessor):
    def __init__(self):
        self.SOURCE = "软科"
        self.university_info_use_year = 2022

    async def parse_and_save_data(self, response):
        '''
        用软科的排名数据更新院校主表的排名
        :param year:
        :param response:
        :return:
        '''
        result = re.findall(r"\(function(.+?)\);", response)
        if result:
            js = "(function" + result[0]
            os.environ["EXECJS_RUNTIME"] = "JScript"
            result_json = execjs.eval(js)
            year = str(result_json["data"][0]["year"])
            all_data = result_json["data"][0]["univData"]
            for university_data in all_data:
                university_uid = self.generate_school_uid(university_data['univNameCn'])
                university_rank = university_data["rankOverall"]
                mapping = db.MysqlMapping("tb_university_info")
                result = await mapping.query({"university_uid": university_uid}, ["id"])
                if result and year == self.university_info_use_year:
                    await mapping.update({"university_rank": university_rank}, {"id": result[0][0]})
                await self._save_university_rank(year, university_uid, university_data)

    async def _save_university_rank(self, year, university_uid, university_data):
        logger.info(university_data)
        mapping = db.MysqlMapping("tb_university_ranking")
        old_data = await mapping.query(
            {"university_uid": university_uid, "ranking_year": year, "ranking_source": self.SOURCE}, ["id"])
        university_name = university_data['univNameCn']
        if old_data:
            logger.info(f"[{university_name}]数据已存在!")
            return
        data = {
            "university_uid": university_uid,
            "university_name": university_name,
            "ranking_sort": str(university_data["rankOverall"]),
            "ranking_year": year,
            "ranking_score": university_data['score'] if university_data['score'] else 0,
            "university_type": university_data['univCategory'],
            "university_tags": " ".join(university_data['univTags']),
            "ranking_source": self.SOURCE,
        }
        await mapping.insert(data)
